﻿using System;
using System.Collections.Generic;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;
using FBroSharp;            // ⚠️ #1 MOST CRITICAL! FBroSharpControl, FBroSharpBrowserListControl
using FBroSharp.Lib;        // ⚠️ CRITICAL! IFBroSharpBrowser, IFBroSharpFrame
using FBroSharp.Value;      // ⚠️ CRITICAL! FBroSharpWindowsInfo, FBroSharpBrowserSetting
using FBroSharp.Event;      // FBroSharpBrowserEvent
using FBroSharp.DataType;   // ⚠️ REQUIRED! FBroSharpEventDisableControl (struct!)
using FBroSharp.Const;      // FBroSharpTransitionType
using FBroSharp.Callback;   // Callback types

namespace WebSocket监控器
{
    public partial class Form1 : Form
    {
        private const string BROWSER_USER_FLAG = "ws_monitor_browser";
        private const string SERVER_ID = "127.0.0.1_7777";
        private List<WebSocketMessage> allMessages = new List<WebSocketMessage>();
        private List<WebSocketMessage> replayMessages = new List<WebSocketMessage>();
        private bool isReplaying = false;
        private IFBroSharpServer serverInstance = null;
        private FBroServerHandler serverHandler = null;

        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            // 创建浏览器
            CreateBrowser();
        }

        /// <summary>
        /// 创建浏览器实例
        /// </summary>
        private void CreateBrowser()
        {
            try
            {
                // 创建窗口信息（嵌入式浏览器）
                FBroSharpWindowsInfo windowInfo = new FBroSharpWindowsInfo
                {
                    parent_window = panelBrowser.Handle,  // ⚠️ CRITICAL for embedded browser!
                    x = 0,
                    y = 0,
                    width = panelBrowser.Width,
                    height = panelBrowser.Height,
                    window_name = "WebSocket 监控浏览器"
                };

                // 创建浏览器设置
                FBroSharpBrowserSetting settings = new FBroSharpBrowserSetting();

                // 创建浏览器事件处理器
                BrowserEvent browserEvent = new BrowserEvent(this);

                // ⚠️ CRITICAL: 使用 default 而不是 null 作为 event_control 参数（struct 类型）
                bool success = FBroSharpControl.CreatBrowser(
                    txtUrl.Text,
                    windowInfo,
                    settings,
                    null,      // request_context
                    null,      // extra_info
                    browserEvent,
                    default,   // ✅ event_control - 使用 default
                    BROWSER_USER_FLAG
                );

                if (!success)
                {
                    MessageBox.Show("浏览器创建失败", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    return;
                }

                UpdateStatus("正在创建浏览器...");
            }
            catch (Exception ex)
            {
                MessageBox.Show($"创建浏览器失败: {ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        /// <summary>
        /// ⚠️ MANDATORY: 处理嵌入式浏览器的窗口大小调整
        /// </summary>
        private void Form1_Resize(object sender, EventArgs e)
        {
            ResizeEmbeddedBrowser();
        }

        /// <summary>
        /// 调整嵌入式浏览器大小
        /// </summary>
        private void ResizeEmbeddedBrowser()
        {
            try
            {
                var browser = FBroSharpBrowserListControl.GetBrowserFromFlag(BROWSER_USER_FLAG);
                if (browser != null && browser.IsValid)  // ⚠️ IsValid is PROPERTY, not method!
                {
                    browser.MoveWindow(0, 0, panelBrowser.Width, panelBrowser.Height, true);
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine($"调整浏览器大小失败: {ex.Message}");
            }
        }

        // ==================== 导航控制 ====================

        private void btnBack_Click(object sender, EventArgs e)
        {
            try
            {
                var browser = FBroSharpBrowserListControl.GetBrowserFromFlag(BROWSER_USER_FLAG);
                if (browser != null && browser.IsValid)
                {
                    browser.GoBack();
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show($"后退失败: {ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void btnForward_Click(object sender, EventArgs e)
        {
            try
            {
                var browser = FBroSharpBrowserListControl.GetBrowserFromFlag(BROWSER_USER_FLAG);
                if (browser != null && browser.IsValid)
                {
                    browser.GoForward();
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show($"前进失败: {ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void btnRefresh_Click(object sender, EventArgs e)
        {
            try
            {
                var browser = FBroSharpBrowserListControl.GetBrowserFromFlag(BROWSER_USER_FLAG);
                if (browser != null && browser.IsValid)
                {
                    browser.Reload();
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show($"刷新失败: {ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void btnGo_Click(object sender, EventArgs e)
        {
            NavigateToUrl(txtUrl.Text);
        }

        private void txtUrl_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                NavigateToUrl(txtUrl.Text);
                e.Handled = true;
                e.SuppressKeyPress = true;
            }
        }

        private void NavigateToUrl(string url)
        {
            try
            {
                // 确保 URL 有协议前缀
                if (!url.StartsWith("http://") && !url.StartsWith("https://") && !url.StartsWith("file://"))
                {
                    url = "http://" + url;
                }

                var browser = FBroSharpBrowserListControl.GetBrowserFromFlag(BROWSER_USER_FLAG);
                if (browser != null && browser.IsValid)
                {
                    var frame = browser.GetMainFrame();
                    if (frame != null && frame.IsValid)
                    {
                        frame.LoadURL(url);
                        UpdateStatus("正在加载...");
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show($"导航失败: {ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        // ==================== WebSocket 控制 ====================

        private void btnEnableIntercept_Click(object sender, EventArgs e)
        {
            EnableWebSocketIntercept();
        }

        /// <summary>
        /// 启用 WebSocket 拦截
        /// </summary>
        public void EnableWebSocketIntercept()
        {
            try
            {
                if (BrowserList.data.Count == 0)
                {
                    MessageBox.Show("浏览器实例不存在", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    return;
                }

                var browser = BrowserList.data[0];
                if (browser == null || !browser.IsValid)
                {
                    MessageBox.Show("浏览器实例无效", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    return;
                }

                // 获取VIP控制器
                var vipControl = browser.GetVIPControl();
                if (vipControl == null || !vipControl.IsValid)
                {
                    MessageBox.Show("无法获取VIP控制器，WebSocket拦截需要VIP授权\n\n" +
                        "请在 Program.cs 中设置授权码：\n" +
                        "FBroSharpVIPGlobalControl.SetAuthorizationCode(\"YOUR_VIP_CODE\");",
                        "需要VIP授权", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    return;
                }

                // ⚠️ 关键：启用 WebSocket 拦截（无参数！）
                vipControl.EnableWebsocketFiter();

                // 刷新浏览器使设置生效
                browser.ReloadIgnoreCache();

                MessageBox.Show("WebSocket 拦截已启用\n\n" +
                    "现在访问 WebSocket 应用，消息将被实时监控。\n" +
                    "建议访问: http://www.websocket-test.com",
                    "成功", MessageBoxButtons.OK, MessageBoxIcon.Information);

                UpdateStatus("WebSocket 拦截已启用");
            }
            catch (Exception ex)
            {
                MessageBox.Show($"启用 WebSocket 拦截失败: {ex.Message}\n\n" +
                    "可能原因：\n" +
                    "1. 需要 VIP 授权\n" +
                    "2. 浏览器尚未完全初始化",
                    "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void btnSetModify_Click(object sender, EventArgs e)
        {
            SetWebSocketTextModifier(txtModifyText.Text);
        }

        /// <summary>
        /// 设置 WebSocket 文本修改规则
        /// </summary>
        public void SetWebSocketTextModifier(string newText)
        {
            try
            {
                if (BrowserList.data.Count == 0)
                {
                    MessageBox.Show("浏览器实例不存在", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    return;
                }

                var browser = BrowserList.data[0];
                var processMessageCon = browser.GetOwnProcessMessageControl();
                if (processMessageCon == null || !processMessageCon.IsValid)
                {
                    MessageBox.Show("无法获取进程消息控制器", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    return;
                }

                // 发送修改指令到渲染进程（InitEvent）
                processMessageCon.ServerSendByBrowser("websocketchangetext", Encoding.Default.GetBytes(newText));

                MessageBox.Show($"已设置 WebSocket 文本修改为:\n\n{newText}\n\n" +
                    "下次发送的消息将被自动修改为此内容。",
                    "成功", MessageBoxButtons.OK, MessageBoxIcon.Information);

                UpdateStatus("已设置消息修改规则");
            }
            catch (Exception ex)
            {
                MessageBox.Show($"设置文本修改失败: {ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void btnClearModify_Click(object sender, EventArgs e)
        {
            ClearWebSocketModifiers();
        }

        /// <summary>
        /// 清除所有 WebSocket 修改规则
        /// </summary>
        public void ClearWebSocketModifiers()
        {
            try
            {
                if (BrowserList.data.Count == 0)
                {
                    MessageBox.Show("浏览器实例不存在", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    return;
                }

                var browser = BrowserList.data[0];
                var processMessageCon = browser.GetOwnProcessMessageControl();
                if (processMessageCon == null || !processMessageCon.IsValid)
                {
                    MessageBox.Show("无法获取进程消息控制器", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    return;
                }

                processMessageCon.ServerSendByBrowser("websocketclear", Encoding.Default.GetBytes("clear"));

                MessageBox.Show("已清除所有 WebSocket 修改规则", "成功", MessageBoxButtons.OK, MessageBoxIcon.Information);

                UpdateStatus("已清除修改规则");
            }
            catch (Exception ex)
            {
                MessageBox.Show($"清除修改规则失败: {ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void btnSendMessage_Click(object sender, EventArgs e)
        {
            SendWebSocketMessage(txtSendMessage.Text);
        }

        /// <summary>
        /// 主动发送 WebSocket 消息
        /// </summary>
        public void SendWebSocketMessage(string message)
        {
            try
            {
                if (BrowserList.data.Count == 0)
                {
                    MessageBox.Show("浏览器实例不存在", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    return;
                }

                var browser = BrowserList.data[0];
                var processMessageCon = browser.GetOwnProcessMessageControl();
                if (processMessageCon == null || !processMessageCon.IsValid)
                {
                    MessageBox.Show("无法获取进程消息控制器", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    return;
                }

                processMessageCon.ServerSendByBrowser("websocketsendtext", Encoding.Default.GetBytes(message));

                MessageBox.Show($"已发送 WebSocket 消息:\n\n{message}", "成功", MessageBoxButtons.OK, MessageBoxIcon.Information);

                UpdateStatus("已发送消息");
            }
            catch (Exception ex)
            {
                MessageBox.Show($"发送消息失败: {ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        // ==================== 内置服务器控制 ====================

        private void btnStartServer_Click(object sender, EventArgs e)
        {
            StartServer();
        }

        private void btnStopServer_Click(object sender, EventArgs e)
        {
            StopServer();
        }

        /// <summary>
        /// 启动内置服务器
        /// </summary>
        private void StartServer()
        {
            try
            {
                if (serverInstance != null)
                {
                    MessageBox.Show("服务器已在运行中", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    return;
                }

                // 创建服务器配置
                var config = new ServerConfiguration
                {
                    Host = "127.0.0.1",
                    Port = 7777,
                    MaxConnections = 100,
                    StaticFileRoot = null,  // 不使用静态文件，返回默认页面
                    DefaultFile = "index.html",
                    EnableCORS = true,
                    EnableWebSocket = true
                };

                // 创建服务器处理器（带状态回调）
                serverHandler = new FBroServerHandler(config, (status) =>
                {
                    // 服务器状态回调
                    UpdateStatus(status);
                });

                // ⚠️ 创建 FBro 服务器实例
                // FBroSharpServer.CreateServer 返回 void，服务器实例在 OnServerCreated 回调中获取
                FBroSharpServer.CreateServer(
                    config.Host,
                    config.Port,
                    config.MaxConnections,
                    serverHandler
                );
                
                // 等待服务器创建（服务器会在 OnServerCreated 回调中返回）
                System.Threading.Thread.Sleep(500); // 等待服务器初始化
                
                // 从处理器中获取服务器实例
                serverInstance = serverHandler.GetServerInstance();

                if (serverInstance == null)
                {
                    MessageBox.Show("服务器创建失败\n\n可能原因：\n1. 端口 7777 已被占用\n2. 权限不足",
                        "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    return;
                }

                // 注册到管理器
                ServerInstanceManager.Instance.RegisterServer(SERVER_ID, serverInstance, config);

                lblServerStatus.Text = $"服务器运行中\n地址: {serverInstance.GetAddress()}\nHTTP: http://127.0.0.1:7777\nWebSocket: ws://127.0.0.1:7777";
                lblServerStatus.ForeColor = Color.Green;
                btnStartServer.Enabled = false;
                btnStopServer.Enabled = true;
                UpdateStatus("内置服务器已启动");

                MessageBox.Show("内置服务器已启动\n\n" +
                    "HTTP 地址: http://127.0.0.1:7777\n" +
                    "WebSocket 地址: ws://127.0.0.1:7777\n\n" +
                    "功能说明：\n" +
                    "- 访问 HTTP 地址查看测试页面\n" +
                    "- 使用 WebSocket 地址进行连接测试\n" +
                    "- 服务器支持 Echo 模式（回显消息）\n" +
                    "- 支持 CORS 跨域请求\n\n" +
                    "提示：在浏览器中打开 http://127.0.0.1:7777 测试！",
                    "成功", MessageBoxButtons.OK, MessageBoxIcon.Information);

                Console.WriteLine($"✅ FBro 服务器已启动: {serverInstance.GetAddress()}");
            }
            catch (Exception ex)
            {
                MessageBox.Show($"启动服务器失败: {ex.Message}\n\n堆栈跟踪:\n{ex.StackTrace}",
                    "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                serverInstance = null;
            }
        }

        /// <summary>
        /// 停止内置服务器
        /// </summary>
        private void StopServer()
        {
            try
            {
                if (serverInstance != null)
                {
                    // 从管理器中停止并移除
                    ServerInstanceManager.Instance.StopServer(SERVER_ID);
                    serverInstance.Dispose();
                    serverInstance = null;
                    serverHandler = null;
                }

                lblServerStatus.Text = "服务器未启动";
                lblServerStatus.ForeColor = Color.Gray;
                btnStartServer.Enabled = true;
                btnStopServer.Enabled = false;
                UpdateStatus("内置服务器已停止");

                MessageBox.Show("内置服务器已停止", "成功", MessageBoxButtons.OK, MessageBoxIcon.Information);

                Console.WriteLine("✅ FBro 服务器已停止");
            }
            catch (Exception ex)
            {
                MessageBox.Show($"停止服务器失败: {ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        // ==================== 消息显示和过滤 ====================

        private void btnClearMessages_Click(object sender, EventArgs e)
        {
            txtMessages.Clear();
            allMessages.Clear();
            UpdateStatus("消息已清空");
        }

        private void txtFilter_TextChanged(object sender, EventArgs e)
        {
            ApplyFilter();
        }

        /// <summary>
        /// 应用过滤器
        /// </summary>
        private void ApplyFilter()
        {
            try
            {
                string filterText = txtFilter.Text.ToLower();
                bool showSend = chkFilterSend.Checked;
                bool showReceive = chkFilterReceive.Checked;

                txtMessages.Clear();

                foreach (var msg in allMessages)
                {
                    // 类型过滤
                    if (msg.Type == "发送" && !showSend)
                        continue;
                    if (msg.Type == "接收" && !showReceive)
                        continue;

                    // 文本过滤
                    if (!string.IsNullOrEmpty(filterText))
                    {
                        if (!msg.Content.ToLower().Contains(filterText))
                            continue;
                    }

                    AppendMessageToDisplay(msg);
                }

                if (chkAutoScroll.Checked)
                {
                    txtMessages.SelectionStart = txtMessages.Text.Length;
                    txtMessages.ScrollToCaret();
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine($"应用过滤器失败: {ex.Message}");
            }
        }

        /// <summary>
        /// 添加 WebSocket 消息（由 BrowserEvent 调用）
        /// </summary>
        public void AddWebSocketMessage(string data)
        {
            if (InvokeRequired)
            {
                Invoke(new Action(() => AddWebSocketMessage(data)));
                return;
            }

            try
            {
                // 解析消息数据：格式 "类型||数据类型||内容||长度"
                string[] parts = data.Split(new[] { "||" }, StringSplitOptions.None);

                if (parts.Length >= 3)
                {
                    string msgType = parts[0];  // "发送" 或 "接收" 或 "WebSocket连接" 或 "WebSocket关闭"
                    
                    if (msgType == "WebSocket连接")
                    {
                        var msg = new WebSocketMessage
                        {
                            Type = "连接",
                            Content = $"WebSocket 已连接: {parts[1]}",
                            Timestamp = DateTime.Now
                        };
                        allMessages.Add(msg);
                        AppendMessageToDisplay(msg);
                    }
                    else if (msgType == "WebSocket关闭")
                    {
                        var msg = new WebSocketMessage
                        {
                            Type = "关闭",
                            Content = $"WebSocket 已关闭: {parts[1]}",
                            Timestamp = DateTime.Now
                        };
                        allMessages.Add(msg);
                        AppendMessageToDisplay(msg);
                    }
                    else if (msgType == "发送" || msgType == "接收")
                    {
                        string dataType = parts[1];  // 0=文本，1=二进制
                        string content = parts.Length > 2 ? parts[2] : "";
                        string length = parts.Length > 3 ? parts[3] : "0";

                        var msg = new WebSocketMessage
                        {
                            Type = msgType,
                            Content = content,
                            DataType = dataType == "0" ? "文本" : "二进制",
                            Length = int.Parse(length),
                            Timestamp = DateTime.Now
                        };

                        allMessages.Add(msg);
                        
                        // 添加到重放列表
                        if (msgType == "发送")
                        {
                            replayMessages.Add(msg);
                            if (lstReplayMessages.InvokeRequired)
                            {
                                lstReplayMessages.Invoke(new Action(() =>
                                {
                                    lstReplayMessages.Items.Add($"[{msg.Timestamp:HH:mm:ss}] {msg.Content}");
                                }));
                            }
                            else
                            {
                                lstReplayMessages.Items.Add($"[{msg.Timestamp:HH:mm:ss}] {msg.Content}");
                            }
                        }

                        AppendMessageToDisplay(msg);
                    }
                }

                if (chkAutoScroll.Checked)
                {
                    txtMessages.SelectionStart = txtMessages.Text.Length;
                    txtMessages.ScrollToCaret();
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine($"添加 WebSocket 消息失败: {ex.Message}");
            }
        }

        /// <summary>
        /// 将消息添加到显示区域
        /// </summary>
        private void AppendMessageToDisplay(WebSocketMessage msg)
        {
            Color color = Color.Lime;
            string prefix = "";

            switch (msg.Type)
            {
                case "发送":
                    color = Color.Yellow;
                    prefix = "↑ 发送";
                    break;
                case "接收":
                    color = Color.Cyan;
                    prefix = "↓ 接收";
                    break;
                case "连接":
                    color = Color.LimeGreen;
                    prefix = "● 连接";
                    break;
                case "关闭":
                    color = Color.Red;
                    prefix = "● 关闭";
                    break;
            }

            string text = $"[{msg.Timestamp:HH:mm:ss.fff}] {prefix}";
            
            if (!string.IsNullOrEmpty(msg.DataType) && msg.Type != "连接" && msg.Type != "关闭")
            {
                text += $" [{msg.DataType}, {msg.Length} 字节]";
            }
            
            text += $"\n{msg.Content}\n\n";

            txtMessages.SelectionStart = txtMessages.TextLength;
            txtMessages.SelectionLength = 0;
            txtMessages.SelectionColor = color;
            txtMessages.AppendText(text);
            txtMessages.SelectionColor = txtMessages.ForeColor;
        }

        // ==================== 消息重放 ====================

        private void btnReplaySelected_Click(object sender, EventArgs e)
        {
            ReplaySelectedMessage();
        }

        private void btnReplayAll_Click(object sender, EventArgs e)
        {
            ReplayAllMessages();
        }

        private void btnClearReplay_Click(object sender, EventArgs e)
        {
            replayMessages.Clear();
            lstReplayMessages.Items.Clear();
            UpdateStatus("重放列表已清空");
        }

        /// <summary>
        /// 重放选中的消息
        /// </summary>
        private async void ReplaySelectedMessage()
        {
            if (lstReplayMessages.SelectedIndex < 0)
            {
                MessageBox.Show("请先选择要重放的消息", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return;
            }

            if (isReplaying)
            {
                MessageBox.Show("正在重放中，请等待完成", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return;
            }

            try
            {
                isReplaying = true;
                int index = lstReplayMessages.SelectedIndex;
                
                if (index >= 0 && index < replayMessages.Count)
                {
                    var msg = replayMessages[index];
                    SendWebSocketMessage(msg.Content);
                    
                    UpdateStatus($"已重放消息: {msg.Content.Substring(0, Math.Min(30, msg.Content.Length))}...");
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show($"重放消息失败: {ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            finally
            {
                isReplaying = false;
            }
        }

        /// <summary>
        /// 重放所有消息
        /// </summary>
        private async void ReplayAllMessages()
        {
            if (replayMessages.Count == 0)
            {
                MessageBox.Show("没有可重放的消息", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return;
            }

            if (isReplaying)
            {
                MessageBox.Show("正在重放中，请等待完成", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return;
            }

            try
            {
                isReplaying = true;
                int delay = (int)numReplayDelay.Value;

                UpdateStatus($"开始重放 {replayMessages.Count} 条消息...");

                for (int i = 0; i < replayMessages.Count; i++)
                {
                    var msg = replayMessages[i];
                    SendWebSocketMessage(msg.Content);
                    
                    lstReplayMessages.SelectedIndex = i;
                    UpdateStatus($"重放进度: {i + 1}/{replayMessages.Count}");

                    if (i < replayMessages.Count - 1)
                    {
                        await Task.Delay(delay);
                    }
                }

                UpdateStatus($"重放完成，共 {replayMessages.Count} 条消息");
                MessageBox.Show($"重放完成\n\n共重放 {replayMessages.Count} 条消息", "成功", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
            catch (Exception ex)
            {
                MessageBox.Show($"重放失败: {ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            finally
            {
                isReplaying = false;
            }
        }

        // ==================== UI 更新方法（由 BrowserEvent 调用）====================

        /// <summary>
        /// 更新状态栏
        /// </summary>
        public void UpdateStatus(string status)
        {
            if (InvokeRequired)
            {
                Invoke(new Action(() => UpdateStatus(status)));
                return;
            }

            lblStatus.Text = status;
        }

        /// <summary>
        /// 更新 URL 显示
        /// </summary>
        public void UpdateUrl(string url)
        {
            if (InvokeRequired)
            {
                Invoke(new Action(() => UpdateUrl(url)));
                return;
            }

            txtUrl.Text = url;
        }

        /// <summary>
        /// 更新窗口标题
        /// </summary>
        public void UpdateTitle(string title)
        {
            if (InvokeRequired)
            {
                Invoke(new Action(() => UpdateTitle(title)));
                return;
            }

            this.Text = $"{title} - WebSocket 监控浏览器";
        }

        /// <summary>
        /// 更新导航按钮状态
        /// </summary>
        public void UpdateNavigationButtons(bool canGoBack, bool canGoForward)
        {
            if (InvokeRequired)
            {
                Invoke(new Action(() => UpdateNavigationButtons(canGoBack, canGoForward)));
                return;
            }

            btnBack.Enabled = canGoBack;
            btnForward.Enabled = canGoForward;
        }

        /// <summary>
        /// 重载：仅用于 OnLoadingStateChange
        /// </summary>
        public void UpdateNavigationButtons()
        {
            try
            {
                var browser = FBroSharpBrowserListControl.GetBrowserFromFlag(BROWSER_USER_FLAG);
                if (browser != null && browser.IsValid)
                {
                    btnBack.Enabled = browser.CanGoBack();
                    btnForward.Enabled = browser.CanGoForward();
                }
            }
            catch
            {
                // 忽略错误
            }
        }
    }

    // ==================== 辅助类 ====================

    /// <summary>
    /// WebSocket 消息数据结构
    /// </summary>
    public class WebSocketMessage
    {
        public string Type { get; set; }        // "发送" 或 "接收" 或 "连接" 或 "关闭"
        public string Content { get; set; }     // 消息内容
        public string DataType { get; set; }    // "文本" 或 "二进制"
        public int Length { get; set; }         // 数据长度
        public DateTime Timestamp { get; set; } // 时间戳
    }
}
